//
//  BuyMemberController.m
//  LYouSubscribeApp
//
//  Created by grx on 2018/12/13.
//  Copyright © 2018年 grx. All rights reserved.
//

#import "LYouBuyMemberController.h"
#import "YQInAppPurchaseTool.h"
#import "LYouBuyInfoView.h"
#import "LYouXyWebController.h"

@interface LYouBuyMemberController ()<YQInAppPurchaseToolDelegate>

@property(nonatomic,strong) UIButton *backButton;
@property(nonatomic,strong) UIButton *smallBackButton;

@property(nonatomic,strong) UIImageView *bgImageView;
@property(nonatomic,strong) UIButton *freeUserButton;
@property(nonatomic,strong) LYouBuyInfoView *infoView;
@property(nonatomic,strong) YQInAppPurchaseTool *IAPTool;

@end

@implementation LYouBuyMemberController

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.isFromSetting==YES) {
        self.gk_interactivePopDisabled = NO;
    }else{
        self.gk_interactivePopDisabled = YES;
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.gk_interactivePopDisabled = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.bgImageView];
    /** 添加描述信息 */
    self.infoView = [LYouBuyInfoView new];
    [self.bgImageView addSubview:self.infoView];
    [self.infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.bgImageView);
        make.top.equalTo(self.bgImageView).offset(0);
        make.height.mas_equalTo(SCREEN_HEIGHT-80);
    }];
    /** 跳转到协议 */
    WeakSelf(weakSelf);
    self.infoView.pushXyControllerBlock = ^(NSInteger tag) {
        LYouXyWebController *xyVC = [[LYouXyWebController alloc]init];
        xyVC.selType = tag;
        [weakSelf.navigationController pushViewController:xyVC animated:YES];
    };
    
    [self.view addSubview:self.backButton];
    [self.backButton setFtCornerdious:30/2 Corners:UIRectCornerTopRight|UIRectCornerBottomRight];
    [self.backButton addSubview:self.smallBackButton];
    /** 控制不同入口点击热区 */
    if (self.isFromSetting==YES) {
        self.smallBackButton.hidden = YES;
    }else{
        self.smallBackButton.hidden = NO;
    }
    
    [self.view addSubview:self.freeUserButton];
    CGFloat safeBottem = MainWindows.safeAreaInsets.bottom;
    CGFloat hight = -38;
    if (safeBottem>0) {
        hight = -55;
    }
    [self.freeUserButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.bottom.equalTo(self.view).offset(hight);
        make.height.mas_equalTo(50);
    }];
    /** 价格 */
    UILabel *priceLable = [[UILabel alloc]init];
    priceLable.text = @"￡30.99/yearly after 7 days free trail!";
    priceLable.textAlignment = NSTextAlignmentCenter;
    priceLable.font = LYFont_Medium(12);
    priceLable.textColor = [UIColor whiteColor];
    [self.view addSubview:priceLable];
    [priceLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.freeUserButton.mas_bottom).offset(3);
        make.height.mas_equalTo(30);
    }];
    if ([ISCheckIOS isEqualToString:@"no"]) {
        priceLable.alpha = 0.6;
    }
    /** 初始化内购 */
    //获取单例
    self.IAPTool = [YQInAppPurchaseTool defaultTool];
    //设置代理
    self.IAPTool.delegate = self;
    //购买后，向苹果服务器验证一下购买结果。默认为YES。不建议关闭
    self.IAPTool.CheckAfterPay = NO;
    /** 恢复购买 */
    self.infoView.recoverBuyBlock = ^{
        [weakSelf.IAPTool restorePurchase];
    };
}
#pragma mark --------YQInAppPurchaseToolDelegate
//IAP工具已获得可购买的商品
-(void)IAPToolGotProducts:(NSMutableArray *)products {
    NSLog(@"GotProducts:===========%@",products);
    if (products.count==0) {
        [LYouLoadingView hide];
        [EasyShowTextView showText:@"无法获取商品信息！"];
        return;
    }
    [[YQInAppPurchaseTool defaultTool]buyProduct:APPSTORYBUYID];
}
//支付失败/取消
-(void)IAPToolCanceldWithProductID:(NSString *)productID {
    [LYouLoadingView hide];
    NSLog(@"canceld:%@",productID);
}
//支付成功了，并开始向苹果服务器进行验证（若CheckAfterPay为NO，则不会经过此步骤）
-(void)IAPToolBeginCheckingdWithProductID:(NSString *)productID {
    NSLog(@"BeginChecking:%@",productID);
    [LYouLoadingView hide];
    [EasyShowTextView showText:@"购买成功，正在验证购买"];
}
//商品被重复验证了
-(void)IAPToolCheckRedundantWithProductID:(NSString *)productID {
    NSLog(@"CheckRedundant:%@",productID);
    [LYouLoadingView hide];
    [EasyShowTextView showText:@"重复验证了"];
}
//商品完全购买成功且验证成功了。（若CheckAfterPay为NO，则会在购买成功后直接触发此方法）
-(void)IAPToolBoughtProductSuccessedWithProductID:(NSString *)productID
                                          andInfo:(NSDictionary *)infoDic {
    NSLog(@"BoughtSuccessed:%@",productID);
    NSLog(@"successedInfo:%@",infoDic);
    /** 本地服务器校验 */
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:0];
    if (encodeStr.length==0) {
        encodeStr = @"";
    }
    NSDictionary *parms = @{@"receipt-data":encodeStr,@"password":SHAREKEY};
    [self requestAppStoreServer:parms];
}
//商品购买成功了，但向苹果服务器验证失败了
//2种可能：
//1，设备越狱了，使用了插件，在虚假购买。
//2，验证的时候网络突然中断了。（一般极少出现，因为购买的时候是需要网络的）
-(void)IAPToolCheckFailedWithProductID:(NSString *)productID
                               andInfo:(NSData *)infoData {
    NSLog(@"CheckFailed:%@",productID);
    [LYouLoadingView hide];
    [EasyShowTextView showText:@"验证失败了"];
}
//恢复了已购买的商品（仅限永久有效商品）
-(void)IAPToolRestoredProductID:(NSString *)productID {
    NSLog(@"Restored:%@",productID);
    [LYouLoadingView hide];
    [self.freeUserButton setUserInteractionEnabled:NO];
    [self.freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButtonSel"] forState:UIControlStateNormal];
    [self.freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButtonSel"] forState:UIControlStateHighlighted];
    [self.freeUserButton setTitle:@"已订阅" forState:UIControlStateNormal];
    NSUserDefaults *isHaveBuy = [NSUserDefaults standardUserDefaults];
    [isHaveBuy setValue:@"yes" forKey:@"ISHAVEBUYMEMBER"];
}
//内购系统错误了
-(void)IAPToolSysWrong {
    NSLog(@"SysWrong");
    [LYouLoadingView hide];
    [EasyShowTextView showText:@"内购系统出错"];
}

#pragma mark - 懒加载
- (UIButton *)freeUserButton {
    if (!_freeUserButton) {
        _freeUserButton = [UIButton new];
        _freeUserButton.layer.cornerRadius = 8;
        _freeUserButton.titleLabel.font = LYFont_Medium(18);
        [_freeUserButton addTarget:self action:@selector(freeUserButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        if ([ISHAVEBUYMEMBER isEqualToString:@"yes"]) {
            /** 已经订阅 */
            [_freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButtonSel"] forState:UIControlStateNormal];
            [_freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButtonSel"] forState:UIControlStateHighlighted];
            [_freeUserButton setUserInteractionEnabled:NO];
            [_freeUserButton setTitle:@"已订阅" forState:UIControlStateNormal];
        }else{
            [_freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButton"] forState:UIControlStateNormal];
            [_freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButton"] forState:UIControlStateHighlighted];
            [_freeUserButton setUserInteractionEnabled:YES];
            [_freeUserButton setTitle:@"免费试用" forState:UIControlStateNormal];
        }
    }
    return _freeUserButton;
}

- (UIButton *)backButton {
    if (!_backButton) {
        CGFloat safeBottem = MainWindows.safeAreaInsets.bottom;
        CGFloat hight = 28;
        if (safeBottem>0) {
            hight = 48;
        }
        _backButton = [UIButton new];
        _backButton.alpha = 0.8;
        _backButton.frame = CGRectMake(0, hight, 45, 35);
        [_backButton setImage:[UIImage imageNamed:@"backLeftBg"] forState:UIControlStateNormal];
        [_backButton setImage:[UIImage imageNamed:@"backLeftBg"] forState:UIControlStateHighlighted];
        [_backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (UIButton *)smallBackButton {
    if (!_smallBackButton) {
        _smallBackButton = [UIButton new];
        _smallBackButton.frame = CGRectMake(0, 5, 10, 25);
        [_smallBackButton addTarget:self action:@selector(smallBackButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _smallBackButton;
}

-(UIImageView *)bgImageView{
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
        _bgImageView.image = [UIImage imageNamed:@"setXyBgImage"];
        _bgImageView.userInteractionEnabled = YES;
    }
    return _bgImageView;
}

-(void)backButtonClick:(UIButton *)sender{
    if ([ISCheckIOS isEqualToString:@"no"]) {
        /** 控制不同入口点击热区 */
        if (self.isFromSetting==YES) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)smallBackButtonClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 开始购买发起内购
-(void)freeUserButtonClick:(UIButton *)sender{
    /** 发起内购 */
    //向苹果询问哪些商品能够购买
    [self.IAPTool requestProductsWithProductArray:@[APPSTORYBUYID]];
    [LYouLoadingView show];
}

#pragma mark - 恢复已购买的商品
-(void)restoreProduct{
    
    [EasyShowTextView showText:@"正在恢复已购商品"];
    //直接调用
    [[YQInAppPurchaseTool defaultTool]restorePurchase];
}

#pragma mark - 服务器校验支付成功凭证
-(void)requestAppStoreServer:(NSDictionary *)parms{
    
    NSString *url = [NSString stringWithFormat:@"%@/iosCheck",LYBASEURL];
    [[LYouNetClient sharedInstance]NetRequestPOSTWithRequestURL:url WithParameter:parms WithReturnValeuBlock:^(NSURLSessionDataTask *task, id  _Nullable responseObject, NSArray *responseDict) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSString *codeStr = [NSString stringWithFormat:@"%@",dic[@"status"]];
        
        
        if ([codeStr isEqualToString:@"0"]) {
            /** 服务器购买校验成功 */
            self.freeUserButton.enabled = NO;
            [self.freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButtonSel"] forState:UIControlStateNormal];
            [self.freeUserButton setBackgroundImage:[UIImage imageNamed:@"freeUserButtonSel"] forState:UIControlStateHighlighted];
            [self.freeUserButton setTitle:@"已订阅" forState:UIControlStateNormal];
            NSUserDefaults *isHaveBuy = [NSUserDefaults standardUserDefaults];
            [isHaveBuy setValue:@"yes" forKey:@"ISHAVEBUYMEMBER"];
        }else{
            [EasyShowTextView showText:@"购买凭证服务器校验失败！"];
        }
        [LYouLoadingView hide];
    } WithErrorBlock:^(NSURLSessionDataTask *task, NSError *error) {
        [LYouLoadingView hide];
    } WithFailureBlock:^{
        [LYouLoadingView hide];

    }];
}

@end
